# coding: utf-8

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header

# 设置smtplib所需的参数
# 下面的发件人，收件人是用于邮件传输的。
smtpserver = 'smtp.qq.com'
username = '772084279@qq.com'
password = 'ontxezslzngpbcei'
sender = '772084279@qq.com'

# 收件人为多个收件人
receiver = ['772084279@qq.com', '857176475@qq.com']

subject = 'Python email test'
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = '772084279@qq.com'

msg['To'] = ";".join(receiver)
msg['Date'] = '2020-10-18'

# 构造文字内容
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain)

# 构造图片链接
sendimagefile = open(r'780.jpg', 'rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = 'attachment; filename="test.png"'
msg.attach(image)

# 构造html
# 发送正文中的图片:由于包含未被许可的信息，网易邮箱定义为垃圾邮件，报554 DT:SPM ：<p><img src="cid:image1"></p>
html = """
<html>  
  <head></head>  
  <body>  
    <p>Hi!<br>  
       How are you?<br>  
       Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> 
    </p> 
  </body>  
</html>  
"""
text_html = MIMEText(html, 'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="text.html"'
msg.attach(text_html)

# 构造附件
sendfile = open(r'11.txt', 'rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')
text_att["Content-Type"] = 'application/octet-stream'
text_att.add_header('Content-Disposition', 'attachment', filename='python附件.txt')
msg.attach(text_att)

smtp = None
# 发送邮件
try:
    smtp = smtplib.SMTP()
    smtp.connect('smtp.qq.com')
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    print("发送成功！")
except Exception as e:
    print(e.__traceback__())
finally:
    smtp.quit()
